package com.Nuyoah.demo01.controller;

import com.Nuyoah.demo01.DTO.PostPageQry;
import com.Nuyoah.demo01.common.JsonResult;
import com.Nuyoah.demo01.entity.Post;
import com.Nuyoah.demo01.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class LoadingController {

    @Autowired
    private PostService postService;

    /**
     * 根据id查询帖子
     *
     * @return 帖子信息
     */
    @PostMapping("/getById")
    public JsonResult<Post> getPostById(@RequestParam("post_id") Integer id) {
        Post post = postService.getPostById(id);
        if (post != null) {
            return new JsonResult<>("200",post, "查询成功");
        } else {
            return new JsonResult<>("1", "帖子不存在");
        }
    }

    /**
     * 查询所有帖子
     *
     * @return 帖子信息列表
     */
    @PostMapping("/getAll")
    public JsonResult<List<Post>> getAllPosts() {
        List<Post> posts = postService.getAllPosts();
        if (posts != null && !posts.isEmpty()) {
            return new JsonResult<>("200",posts, "查询成功");
        } else {
            return new JsonResult<>("1", "没有帖子");
        }
    }

    /**
     * 分页查询帖子
     *
     * @return 帖子信息分页列表
     */
    @PostMapping("/getPagePosts")
    public JsonResult<List<Post>> getPagePosts(@RequestBody @Valid PostPageQry qry) {
        return new JsonResult<>("200",postService.selectPagePosts(qry), "查询成功");
    }

    /**
     * 插入帖子
     *
     * @return 插入结果
     */
    @PostMapping("/insert")
    public JsonResult<String> insertPost(@RequestBody Post post) {
        Integer result = postService.insertPost(post);
        if (result > 0) {
            return new JsonResult<>("200", "帖子插入成功");
        } else {
            return new JsonResult<>("1", "帖子插入失败");
        }
    }

    /**
     * 更新帖子
     *
     * @return 更新结果
     */
    @PostMapping("/update")
    public JsonResult<String> updatePost(@RequestBody Post post) {
        Integer result = postService.updatePost(post);
        if (result > 0) {
            return new JsonResult<>("200", "帖子更新成功");
        } else {
            return new JsonResult<>("1", "帖子更新失败");
        }
    }

    /**
     * 删除帖子
     *
     * @return 删除结果
     */
    @PostMapping("/delete")
    public JsonResult<String> deletePost(@RequestParam("id") Integer id) {
        Integer result = postService.deletePost(id);
        if (result > 0) {
            return new JsonResult<>("200", "帖子删除成功");
        } else {
            return new JsonResult<>("1", "帖子删除失败");
        }
    }

    /**
     * 点赞帖子
     *
     *
     */
    //
    @PostMapping("/like")
    public JsonResult<String> likePost(@RequestParam("id") Integer id) {
        return postService.likePost(id);
    }

    /**
     * 评论帖子
     */
    //TODO 待完善

    /**
     * 回复评论
     */
    //TODO 待完善

}